package com.baizhi.controller;

import com.baizhi.entity.PmsAttrGroup;
import com.baizhi.service.IPmsAttrGroupService;
import com.baizhi.vo.PmsAttrGroupListVo;
import com.baizhi.vo.PmsAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yu
 */
@RestController
public class PmsAttrGroupController {
    @Autowired
    private IPmsAttrGroupService pmsAttrGroupService;

    @RequestMapping("/pmsAttrGroups/showAll")
    public Map showByCategoryId(@RequestParam(required = false) Long categoryId, Integer page, Integer limit) {
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<PmsAttrGroup> wrapper = new QueryWrapper<>();

        wrapper.eq("category_id", categoryId);

        Page<PmsAttrGroup> page1 = new Page<>(page, limit);
        Page<PmsAttrGroup> page2 = pmsAttrGroupService.page(page1, wrapper);
        long count = page2.getTotal();
        List<PmsAttrGroup> records = page2.getRecords();
        map.put("code",0);
        map.put("count",count);
        map.put("data",records);

        return map;
    }

    @PostMapping("/pmsAttrGroups")
    public Map insert(@RequestBody PmsAttrGroupVo pmsAttrGroupVo){
        pmsAttrGroupService.insert(pmsAttrGroupVo);
        HashMap<String, Object> map = new HashMap<>();
        map.put("status","success");
        return map;
    }

    @DeleteMapping("/pmsAttrGroups/{id}")
    public Map delete(@PathVariable("id") Integer id){
        HashMap<String, Object> map = new HashMap<>();
        pmsAttrGroupService.removeById(id);
        map.put("status","success");
        return map;
    }

    @GetMapping("/pmsAttrGroups/{id}")
    public Map showByCategoryId(@PathVariable("id") Integer categoryId){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<PmsAttrGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",categoryId);
        List<PmsAttrGroup> list = pmsAttrGroupService.list(wrapper);
        List<PmsAttrGroupListVo> collect = list.stream().map(new Function<PmsAttrGroup, PmsAttrGroupListVo>() {
            @Override
            public PmsAttrGroupListVo apply(PmsAttrGroup pmsAttrGroup) {
                PmsAttrGroupListVo pmsAttrGroupListVo = new PmsAttrGroupListVo();
                BeanUtils.copyProperties(pmsAttrGroup, pmsAttrGroupListVo);
                return pmsAttrGroupListVo;
            }
        }).collect(Collectors.toList());
        map.put("status","success");
        map.put("data",collect);
        return map;
    }


}
